package com.stdio.ui;

import java.util.ArrayList;
import java.util.List;
import com.stdio.R;
import com.stdio.modle.PBInfor;
import com.stdio.modle.PeopleInfo;
import com.stdio.tools.StringMethod;
import com.stdio.view.AlphabetScrollBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;

public class ContactsUI extends Activity implements OnItemClickListener,OnGestureListener,OnTouchListener{

	LayoutInflater mInflater;
	public LinearLayout mContent_view;
	private LinearLayout mContent;
	
	private ListView mContact_list;
	private AlphabetScrollBar mScrollBar;
	private String sInputStr = null;
	private SectionAdapter mAdapter;
	private GestureDetector mDetector;
	private ImageButton mNewcontact;
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.contact_pref);
		mInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		mContent_view = (LinearLayout)findViewById(R.id.content_lv);
		mContent = (LinearLayout)mInflater.inflate(R.layout.contacts_list, null);
		mContent_view.addView(mContent);
		
		mNewcontact = (ImageButton)findViewById(R.id.add_contact);
		mNewcontact.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ContactsUI.this,ContactEditActivity.class);
				startActivity(intent);
			}
			
		});
		
		
		mDetector = new GestureDetector(this);
		mContact_list = (ListView)findViewById(R.id.contactlist);
		mContact_list.setOnTouchListener(this);
		mContact_list.setOnItemClickListener(this);
		
		initListView();
		
		mScrollBar = (AlphabetScrollBar)mContent.findViewById(R.id.contact_scrollbar);
		mScrollBar.setListView(mContact_list);
		
	}

	public void initListView()
	{
		mAdapter = new SectionAdapter(this,getContactData());
		mContact_list.setAdapter(mAdapter);
		//mContact_list.setOnClickListener(mListener);
	}
	
	public List<PeopleInfo> getContactData()
	{
		 PBInfor pi = new PBInfor(this);
	     List<PeopleInfo> mContactList = pi.getContactsList();
	     return mContactList;
	}
	
	class SectionAdapter extends BaseAdapter implements SectionIndexer
	{
		private List<PeopleInfo> mListData = new ArrayList<PeopleInfo>();
		private List<PeopleInfo> mListResouceData = new ArrayList<PeopleInfo>();
		
		public List<PeopleInfo> getmListData() {
			return mListData;
		}

		public void setmListData(List<PeopleInfo> mListData) {
			this.mListData = mListData;
		}
		
		public SectionAdapter(Context context, List<PeopleInfo> list)
		{
			initListData();
			mListData = list;
			//System.arraycopy(list, 0, mListResouceData, 0, list.size());
			copyData(mListData, mListResouceData);
		}
		
		private void initListData() {
			mListData.clear();
		}
		
		@Override
		public int getPositionForSection(int section) {
			// TODO Auto-generated method stub
			if(section < 3)
			{
				return 0;
			}
			else
			{
				for(int i = 0; i < mListData.size();i++)
				{
					char firstChar = ((String)mListData.get(i).getDisplayName()).charAt(0);
					if(firstChar == (section - 3 + 'A'))
					{
						return i + 1;
					}
				}
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object[] getSections() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mListData.size()+1;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (position == 0) {
				return getSearchBar();
			} 
			else
			{
				if(position < (mListData.size()+1))
				{
					return SetSection(convertView, position-1);
				}
			}
			return null;
		}
		
		TextWatcher textWatcher = new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if(s!=null&&s.length()>0)
				{
					String str = s.toString();
					str = StringMethod.getCharacterFromString(str, StringMethod.TYPE_UPPER);
					searchData(str);
					setSearchBarString(str);
					notifyDataUpdate();
				}
				else
				{
					searchData("");
					setSearchBarString("");
					notifyDataUpdate();
				}
			}
			
		};
		
		public void notifyDataUpdate()
		{
			this.notifyDataSetChanged();
		}
		
		public void setSearchBarString(String input) {
			sInputStr = input;
		}

		
		public void searchData(String str)
		{
			mListData.clear();
			for(int i = 0;i < mListResouceData.size(); i++)
			{
				if(str!=null)
				{
					if(mListResouceData.get(i).getDisplayName().contains(str))
					{
						mListData.add(mListResouceData.get(i));
					}
				}
			}
		}
		
		public View getSearchBar()
		{
			View view = (View)mInflater.inflate(R.layout.search_bar, null);
			EditText searchbar = (EditText)view.findViewById(R.id.search_bar_et);
			mNewcontact = (ImageButton)view.findViewById(R.id.add_contact);
			mNewcontact.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(ContactsUI.this,ContactEditActivity.class);
					intent.setAction("android.intent.action.INSERT");
					startActivity(intent);
				}
				
			});
			searchbar.addTextChangedListener(textWatcher);
			Button btnClear = (Button) view.findViewById(R.id.search_clear_bt);
			if(sInputStr!=null&&sInputStr.length()>0)
			{
				searchbar.setText(sInputStr);
				searchbar.requestFocus();
				searchbar.setSelection(sInputStr.length());
				btnClear.setVisibility(View.VISIBLE);
				btnClear.setOnClickListener(mListener);
			}
			else if (sInputStr != null)
			{
				searchbar.setText(sInputStr);
				searchbar.requestFocus();
				searchbar.setSelection(sInputStr.length());
				btnClear.setVisibility(View.GONE);
			}
			return view;
		}
		
		private View SetSection(View convertView,int position)
		{
			View view = mInflater.inflate(R.layout.contact_code_item, null);
			TextView caption = (TextView) view
					.findViewById(R.id.contactitem_catalog);
			
			PeopleInfo info = new PeopleInfo();
			info = mListData.get(position);
			String strName = info.getDisplayName();
			Bitmap contact_icon = info.getBitmap();
			char fistChar = strName.charAt(0);

			if (position == 0) 
			{
				caption.setVisibility(View.VISIBLE);
				caption.setText(String.valueOf(fistChar));
			} 
			else 
			{
				char preChar = ((String) (mListData.get(position - 1)
						.getDisplayName())).charAt(0);
				if (preChar != fistChar)
				{
					caption.setVisibility(View.VISIBLE);
					caption.setText(String.valueOf(fistChar));
				} 
				else 
				{
					caption.setVisibility(View.GONE);
				}
			}

			((ImageView) view.findViewById(R.id.portrait))
					.setImageBitmap(contact_icon);
			((TextView) view.findViewById(R.id.contact_name))
					.setText(strName);
			
			return view;
		}
		
		View.OnClickListener mListener = new View.OnClickListener() {

			public void onClick(View v) 
			{
				switch (v.getId()) 
				{
				case R.id.search_clear_bt:
					setSearchBarString("");
					copyData(mListResouceData, mListData);
					notifyDataUpdate();
					break;
				default:
					break;
				}

			}
		};
		
		
		private void copyData(List<PeopleInfo> resouce,
				List<PeopleInfo> dest) 
		{
			int size = resouce.size();
			dest.clear();
			for (int i = 0; i < size; i++) 
			{
				dest.add(resouce.get(i));
			}
		}
	}

	
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		// TODO Auto-generated method stub
		if(position > 0)
		{
			String contactId = mAdapter.getmListData().get(position-1).getContactId();
			Intent intent = new Intent(ContactsUI.this,ContactDetailActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("contactId", contactId);
			intent.putExtras(bundle);
			startActivity(intent);
			finish();
		}
	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float arg2,
			float arg3) {
		if(e1.getX() < e2.getX()) 
		 {//move to left  
	           //mViewFlipper.showNext();
			   Intent intent = new Intent(ContactsUI.this,CallHistoryActivity.class);
			   startActivity(intent);
	           overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);  
	     }
		// else if(e1.getX() < e2.getX())
		 //{    
//			   Intent intent = new Intent(CallHistoryActivity.this,ContactsUI.class);
//			   startActivity(intent);
//	           overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);  
//	           mViewFlipper.setInAnimation(getApplicationContext(), R.anim.push_right_in);  
//	           mViewFlipper.setOutAnimation(getApplicationContext(), R.anim.push_right_out);  
//	           mViewFlipper.showPrevious();  
//	           mViewFlipper.setInAnimation(getApplicationContext(), R.anim.push_left_in);  
//	           mViewFlipper.setOutAnimation(getApplicationContext(), R.anim.push_left_out);  
	    // }
		 else 
		 {  
	           return false;  
	     }  
	       
		 return true;  
	}

	@Override
	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent event) {
		// TODO Auto-generated method stub
		return this.mDetector.onTouchEvent(event);
	}
	
	
}
